// 全局分页组件
import Pagination from '/components/pagination.js'; 
// 订单头部
import '/order/components/Header/index.js';
// 订单列表
import '/order/api/order_api.js';

let currentPage = 1;
let pageSize = 20;
let pagination;

// 定义所有可导出的列
const exportColumns = [
    { field: 'id', title: '序号' },
    { field: 'shopName', title: '店铺' },
    { field: 'orderNo', title: '订单编号' },
    { field: 'receiverAddress', title: '收件人省市区详细地址' },
    { field: 'receiverName', title: '收件人名称' },
    { field: 'receiverPhone', title: '收件人手机号码' },
    { field: 'expressCompany', title: '快递公司' },
    { field: 'expressNo', title: '快递单号' },
    { field: 'templateName', title: '模板名称' },
    { field: 'orderTime', title: '下单时间' },
    { field: 'payTime', title: '付款时间' },
    { field: 'deliveryTime', title: '发货时间' },
    { field: 'productName', title: '商品简称' },
    { field: 'productProps', title: '销售属性' },
    { field: 'merchantCode', title: '商家编码' },
    { field: 'quantity', title: '商品数量' },
    { field: 'payAmount', title: '支付金额' },
    { field: 'importTime', title: '导入时间' },
    { field: 'updateTime', title: '更新时间' }
];

// 默认导出列
const defaultColumns = [
    'id', 'shopName', 'orderNo', 'receiverName', 'receiverPhone',
    'expressCompany', 'expressNo', 'productName', 'quantity', 'payAmount'
];

// 修改 localStorage 的键名，添加页面标识
const STORAGE_KEY = 'saleDefaultExportColumns';

// 显示导入表单
function showImportForm() {
    document.getElementById('mask').style.display = 'block';
    document.getElementById('importForm').style.display = 'block';
}

// 隐藏导入表单
function hideImportForm() {
    document.getElementById('mask').style.display = 'none';
    document.getElementById('importForm').style.display = 'none';
    // 重置表单
    document.getElementById('uploadForm').reset();
}

// 显示加载提示
function showLoading(text) {
    document.getElementById('loadingText').textContent = text;
    document.getElementById('loadingMask').style.display = 'block';
}

// 隐藏加载提示
function hideLoading() {
    document.getElementById('loadingMask').style.display = 'none';
}

// 上传Excel
function uploadExcel() {
    const formData = new FormData(document.getElementById('uploadForm'));
    showLoading('正在导入数据，请稍候...');
    
    fetch('/saleOrder/import', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        hideLoading();
        if (data.code === 200) {
            alert('导入成功');
            hideImportForm();
            loadData();
        } else {
            alert(data.msg);
        }
    })
    .catch(error => {
        hideLoading();
        alert('导入失败：' + error);
    });
}

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    const path = window.location.pathname;
    document.querySelectorAll('.nav-item').forEach(item => {
        if (item.getAttribute('href') === path) {
            item.classList.add('active');
        }
    });
    
    // 初始化分页组件
    initPagination();
    
    // 加载数据
    loadData();
    
    // 设置事件监听
    setupEventListeners();
    
    // 加载保存的默认导出列
    loadDefaultColumns();
});

// 设置事件监听
function setupEventListeners() {
    // 搜索按钮
    document.getElementById('searchBtn').addEventListener('click', () => {
        currentPage = 1;
        loadData();
    });
    
    // 导入按钮
    document.getElementById('importBtn').addEventListener('click', showImportForm);
    document.getElementById('cancelImportBtn').addEventListener('click', hideImportForm);
    
    // 导出按钮
    document.getElementById('exportBtn').addEventListener('click', showExportForm);
    document.getElementById('cancelExportBtn').addEventListener('click', hideExportForm);
    
    // 导出配置按钮
    document.getElementById('selectAllBtn').addEventListener('click', () => selectAllColumns(true));
    document.getElementById('unselectAllBtn').addEventListener('click', () => selectAllColumns(false));
    document.getElementById('defaultColumnsBtn').addEventListener('click', selectDefaultColumns);
    document.getElementById('confirmExportBtn').addEventListener('click', confirmExport);
    
    // 导入表单提交
    document.getElementById('uploadForm').addEventListener('submit', function(e) {
        e.preventDefault();
        uploadExcel();
    });
}

// 初始化分页组件
function initPagination() {
    pagination = new Pagination({
        container: 'paginationContainer',
        pageSize: 20,
        pageNum: 1,
        total: 0,
        onPageChange: function(page, size) {
            currentPage = page;
            pageSize = size;
            loadData();
        }
    });
}

// 加载默认导出列
function loadDefaultColumns() {
    const savedColumns = localStorage.getItem(STORAGE_KEY);
    if (savedColumns) {
        defaultColumns.splice(0, defaultColumns.length, ...JSON.parse(savedColumns));
    }
}

// 加载数据
function loadData() {
    const keyword = document.getElementById('keyword').value;
    const merchantCode = document.getElementById('merchantCode').value;
    const startTime = document.getElementById('startTime').value;
    const endTime = document.getElementById('endTime').value;
    
    fetch(`/saleOrder/list?pageNum=${currentPage}&pageSize=${pageSize}&keyword=${keyword}&merchantCode=${merchantCode}&startTime=${startTime}&endTime=${endTime}`)
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                renderTable(data.data.list);
                pagination.update({
                    pageNum: data.data.pageNum,
                    pageSize: data.data.pageSize,
                    total: data.data.total,
                    hasNext: data.data.pageNum * data.data.pageSize < data.data.total,
                    hasPrevious: data.data.pageNum > 1
                });
            } else {
                alert(data.msg);
            }
        });
}

// 渲染表格
function renderTable(list) {
    const tbody = document.getElementById('orderList');
    tbody.innerHTML = '';
    
    list.forEach(item => {
        tbody.innerHTML += `
            <tr>
                <td class="tooltip" data-tooltip="${item.id}">${item.id}</td>
                <td class="tooltip" data-tooltip="${item.shopName}">${item.shopName || '-'}</td>
                <td class="tooltip" data-tooltip="${item.orderNo}">${item.orderNo}</td>
                <td class="tooltip" data-tooltip="${item.receiverAddress}">${item.receiverAddress || '-'}</td>
                <td class="tooltip" data-tooltip="${item.receiverName}">${item.receiverName || '-'}</td>
                <td class="tooltip" data-tooltip="${item.receiverPhone}">${item.receiverPhone || '-'}</td>
                <td class="tooltip" data-tooltip="${item.expressCompany}">${item.expressCompany || '-'}</td>
                <td class="tooltip" data-tooltip="${item.expressNo}">${item.expressNo || '-'}</td>
                <td class="tooltip" data-tooltip="${item.templateName}">${item.templateName || '-'}</td>
                <td class="tooltip" data-tooltip="${item.orderTime}">${item.orderTime || '-'}</td>
                <td class="tooltip" data-tooltip="${item.payTime}">${item.payTime || '-'}</td>
                <td class="tooltip" data-tooltip="${item.deliveryTime}">${item.deliveryTime || '-'}</td>
                <td class="tooltip" data-tooltip="${item.productName}">${item.productName || '-'}</td>
                <td class="tooltip" data-tooltip="${item.productProps}">${item.productProps || '-'}</td>
                <td class="tooltip" data-tooltip="${item.merchantCode}">${item.merchantCode || '-'}</td>
                <td class="tooltip" data-tooltip="${item.quantity}">${item.quantity || '-'}</td>
                <td class="tooltip" data-tooltip="${item.payAmount}">${item.payAmount || '-'}</td>
                <td class="tooltip" data-tooltip="${formatDate(item.importTime)}">${formatDate(item.importTime)}</td>
                <td class="tooltip" data-tooltip="${formatDate(item.updateTime)}">${formatDate(item.updateTime)}</td>
            </tr>
        `;
    });
}

// 格式化日期
function formatDate(timestamp) {
    if (!timestamp) return '';
    const date = new Date(timestamp);
    return date.toLocaleString();
}

// 搜索
function search() {
    currentPage = 1;
    loadData();
}

// 显示导出配置
function showExportForm() {
    // 先检查是否有保存的默认列
    const savedColumns = localStorage.getItem(STORAGE_KEY);
    if (savedColumns) {
        defaultColumns.splice(0, defaultColumns.length, ...JSON.parse(savedColumns));
    }

    const columnList = document.getElementById('columnList');
    columnList.innerHTML = exportColumns.map(col => `
        <div class="column-item">
            <input type="checkbox" 
                id="col_${col.field}" 
                value="${col.field}"
                ${defaultColumns.includes(col.field) ? 'checked' : ''}>
            <label for="col_${col.field}">${col.title}</label>
        </div>
    `).join('');
    
    document.getElementById('mask').style.display = 'block';
    document.getElementById('exportForm').style.display = 'block';
}

// 隐藏导出配置
function hideExportForm() {
    document.getElementById('mask').style.display = 'none';
    document.getElementById('exportForm').style.display = 'none';
}

// 全选/取消全选
function selectAllColumns(checked) {
    document.querySelectorAll('#columnList input[type="checkbox"]')
        .forEach(checkbox => checkbox.checked = checked);
}

// 选择默认列
function selectDefaultColumns() {
    // 先检查是否有保存的默认列
    const savedColumns = localStorage.getItem(STORAGE_KEY);
    if (savedColumns) {
        defaultColumns.splice(0, defaultColumns.length, ...JSON.parse(savedColumns));
    }
    
    document.querySelectorAll('#columnList input[type="checkbox"]')
        .forEach(checkbox => checkbox.checked = defaultColumns.includes(checkbox.value));
}

// 确认导出
function confirmExport() {
    const selectedColumns = Array.from(document.querySelectorAll('#columnList input:checked'))
        .map(checkbox => checkbox.value);
    
    if (selectedColumns.length === 0) {
        alert('请至少选择一列进行导出');
        return;
    }
    
    const keyword = document.getElementById('keyword').value;
    const merchantCode = document.getElementById('merchantCode').value;
    const startTime = document.getElementById('startTime').value;
    const endTime = document.getElementById('endTime').value;
    
    // 如果选中了"保存为默认选项"
    if (document.getElementById('saveAsDefault').checked) {
        localStorage.setItem(STORAGE_KEY, JSON.stringify(selectedColumns));
    }
    
    showLoading('正在导出数据，请稍候...');
    
    const url = `/saleOrder/export?keyword=${keyword}&merchantCode=${merchantCode}&startTime=${startTime}&endTime=${endTime}&columns=${selectedColumns.join(',')}`;
    
    fetch(url)
        .then(response => {
            hideLoading();
            if (response.ok) {
                // 创建一个隐藏的a标签来下载文件
                const a = document.createElement('a');
                a.href = url;
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
            } else {
                throw new Error('导出失败');
            }
        })
        .catch(error => {
            hideLoading();
            alert('导出失败：' + error);
        });
    
    hideExportForm();
}

// 修改原有的导出按钮事件
export function exportExcel() {
    showExportForm();
}